package org.nfIt.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.lang.UUID;
import org.nfIt.service.ValidateCodeVoService;
import org.nfIt.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * ClossName:ValidateCodeVoServiceImpl
 * Pakage:org.nfIt.service.impl
 * Description
 *
 * @Author L
 * @Create 2024/6/18 17:52
 * @Version 2023.1.3
 */
@Service
public class ValidateCodeVoServiceImpl implements ValidateCodeVoService {

    /**
     * redis
     */
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 生成图片验证码
     * @return
     */
    @Override
    public ValidateCodeVo generateValidateCode() {

        //1 通过hutool-all工具生成图片验证码
        //int width 宽度, int height 高度, int codeCount 位数, int circleCount 干扰线
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String codeValue = circleCaptcha.getCode();//4位验证码的值（如: k 3 3 0）
        String imageBase64 = circleCaptcha.getImageBase64();//返回图片验证码,也是经过Base64位编码加密的值

        //2 把验证码存储到redis里面，设置redis的key:uuid, redis的value :验证码值
        //replaceAll("-", ""); : 把 "-" 替换为 ""
        String key = UUID.randomUUID().toString().replaceAll("-", "");

        //设置redis时间
        redisTemplate.opsForValue().set("user:Validate"+key ,codeValue ,5 , TimeUnit.MINUTES);
        //3 返回ValidateCodevo对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);//redis中的key
        //表示是一个图片类型的验证码
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);

        return validateCodeVo;
    }
}
